import base64
import config
import eventlet
import pickle
from jobs.HoldLogin import SendMessage, send_email, clear_friends, send_email_register,freeClear
from libs import itchat
import math
import os
import re
import time
from utils.Base import Page
from common.alipayCom import AliPayComponent
from apps.crm.models import ShareHistory, Order, Order2Product, UseNumber, Setting
from flask.views import MethodView, View
from flask import (
    g,
    render_template,
    redirect,
    url_for,
    Response,
    request,
    jsonify,
    session,
    send_from_directory,
    current_app
)
from flask_restful import Resource, marshal_with, marshal
from application import db, redis
from .forms import LoginForm, EditMessageForm
from .models import (
    FrontUser,
    Swiper,
    Desc,
    OursGoodness,
    ProductExamples,
    Article,
    Product,
    ProductType,
    Tutorials,
    Distribution,
    TransferHistory
)
from .fields import *
from .inputs import *
com = re.compile(r'nickname="(.*?)"')


class Login(MethodView):

    def get(self):
        if session.get('user_id'):
            return redirect(url_for('.index'))
        return render_template('front/login.html', title='登陆')

    def post(self):
        forms = LoginForm(request.form)
        if forms.validate():
            username = forms.data['username']
            password = forms.data['password']
            frontUser = db.session.query(FrontUser).filter(
                FrontUser.login_name == username).first()
            if not frontUser:
                return jsonify(
                    {
                        'code': 403,
                        'message': '找不到用户'
                    }
                )
            if frontUser.status == 2:
                return jsonify(
                    {
                        'code': 403,
                        'message': '用户暂时不能使用请联系管理员'
                    }
                )

            if frontUser.checkPassWord(password):
                session['user_id'] = frontUser.id
                session['type'] = 'front'
                return jsonify(
                    {
                        'code': 200,
                        'message': url_for('.index')
                    }
                )
            else:
                return jsonify(
                    {
                        'code': 403,
                        'message': '用户名或密码错误'
                    }
                )
        else:
            error_message = forms.errors.popitem()
            return jsonify({
                'code': 403,
                'message': error_message[1][0]
            })


class LoginOut(MethodView):

    def get(self):
        session.pop('user_id')
        return redirect(url_for('.login'))


class UploadFile(MethodView):

    def post(self):
        response = {
            "name": '',
            "size": "",
            "url": "",
            "thumbnail_url": "",

        }
        file = request.files['file']

        if os.path.exists(config.UPLOAD_PATH):
            filename = '%s%s' % (str(int(time.time())), file.filename)
            filepath = os.path.join(config.UPLOAD_PATH, filename)

        with open(filepath, 'wb') as f:
            f.write(file.read())
            f.flush()
        response['thumbnail_url'] = url_for('.upload_get', filename=filename)
        response['url'] = url_for('.upload_get', filename=filename)
        return jsonify(response)

    def get(self, filename=None):
        if not filename:
            response = Response('找不到文件', status=404)
            return response
        filepath = os.path.join(config.UPLOAD_PATH, filename)

        if not os.path.exists(filepath):
            response = Response('找不到文件', status=404)
            return response
        return send_from_directory(config.UPLOAD_PATH, filename)


class WangEditorUpload(Resource):

    def post(self):

        response = {

            "errno": 0,
            "data": []
        }
        for i in request.files:
            filename = '%s%s' % (str(int(time.time())), i)
            filepath = os.path.join(config.UPLOAD_PATH, filename)
            with open(filepath, 'wb') as f:
                f.write(request.files[i].read())
                f.flush()
            response['data'].append(
                'http://127.0.0.1:5000'+url_for('.upload_get', filename=filename))
        return response


class GetLoginUuid(Resource):

    def get(self):
        content_header = 'data:image/jpg;base64,'
        response = {
            'code': 200,
            'message': '获取成功',
            'data': {
                'qrcode': '',
                'uuid': ''
            }
        }
        chat = itchat.new_instance()

        uuid = chat.get_QRuuid()
        if not uuid:
            response['code'] = 403
            response['message'] = '获取失败'
            return jsonify(response)

        qrStorage = chat.get_QR(enableCmdQR=False)
        qrStorage.seek(0)
        content = qrStorage.read()
        content = base64.b64encode(content).decode('utf-8')
        response['data']['qrcode'] = content_header + content
        response['data']['uuid'] = uuid
        return response


class CheckLogin(Resource):

    def get(self):
        response = {
            'code': 200,
            'msg': '成功'
        }
        uuid = request.args.get('uuid', '')
        if not uuid:
            response['code'] = 101
            response['msg'] = 101
            return response
        chat = itchat.new_instance()
        chat.uuid = uuid
        try:
            res = chat.check_login(uuid)
        except Exception as e:
            response['code'] = 101
        else:
            response['code'] = int(res)
        return response


class Send(Resource):

    def get(self):
        data = request.args
        chat = itchat.new_instance()
        chat.uuid = data['uuid']
        card_number = data['card_number']
        # ---------------------------------
        chat.check_login(data['uuid'])
        chat.web_init()
        storage = chat.storageClass.dumps()
        strchat = base64.b64encode(pickle.dumps(
            {
                'version': '1.3.10',
                'loginInfo': chat.loginInfo,
                'cookies': chat.s.cookies.get_dict(),
                'storage': storage
            })).decode('utf-8')

        
        if card_number:
            card = db.session.query(UseNumber).filter(UseNumber.card_number == card_number).first()
            
            if card.Order2Product.product.type == 1:
                res = clear_friends.delay(chat=strchat, card_number=card_number)
            else:
                res = SendMessage.delay(chat=strchat, card_number=card_number)
        else:
            res = freeClear.delay(chat=strchat,card_number=data['uuid'])
        # ---------------------------------
        return {
            'code': 200,
            'msg': '运行中。。。',
            'data': {
                'result_id': '%s%s' % ('celery-task-meta-', str(res))
            }
        }


class SendProcess(Resource):

    def get(self):
        card = request.args.get('card_number')
        if card and redis.exists(card):
            result = self.getData(card)

            return {
                'code': 200,
                'msg': '获取成功',
                'data': {
                    'msg': result[0],
                    'check_data': result[1]
                }
            }

        else:
            return {
                'code': 400,
                'msg': '任务已经结束或不存在',
                'data': {
                    'msg': '未找到',
                    'check_data': {}
                }
            }

    def getData(self, card):
        result = redis.rpop(card)
        if result:
            result = pickle.loads(result)
            if result[1] == 'done':
                redis.delete(card)
        return result


class SwiperRource(Resource):

    def get(self):
        result = db.session.query(Swiper).all()

        return marshal({
            'code': 200,
            'msg': '获取成功',
            'data': result,
        }, SwiperFields)

    def put(self):

        data = CreateSwipperInputs.parse_args(req=request)

        S = Swiper(**data)

        db.session.add(S)
        db.session.commit()

        return marshal({
            'code': 200,
            'msg': '获取成功',
            'data': S
        }, OneSwiperFields)

    def delete(self):

        id = request.args.get('id')
        if id:
            swiper = db.session.query(Swiper).filter(Swiper.id == id).first()
            if swiper:
                db.session.delete(swiper)
                db.session.commit()
        return {
            'code': 200,
            'msg': '修改成功',
        }

    def post(self):

        data = UpdateSwipperInputs.parse_args(req=request)
        S = db.session.query(Swiper).filter(Swiper.id == data['id']).first()
        if S:
            S.img = data['img']
            S.link = data['link']
            S.desc = data['desc']
            db.session.commit()
        return {
            'code': 200,
            'msg': '修改成功',
        }


class DescReource(Resource):

    def get(self):
        result = db.session.query(Desc).all()
        P = Page(result)
        return marshal({
            'code': 200,
            'msg': '获取成功',
            'data': P.data,
            'page': P.page_info
        }, DescFields)

    def put(self):
        data = CreateDesc.parse_args(req=request, http_error_code=200)
        try:
            desc = Desc(**request.json)
            db.session.add(desc)
            db.session.commit()
        except Exception as e:
            print(e)
            return {
                'code': 400,
                'msg': '数据异常'
            }
        return marshal({
            'code': 200,
            'msg': '新建成功',
            'data': desc
        }, DescOneFields)

    def delete(self):
        id = request.args.get('id')
        desc = db.session.query(Desc).filter(Desc.id == id).first()
        if desc:
            db.session.delete(desc)
            db.session.commit()
        return {
                'code': 200,
                'msg': '删除成功'
            }

    def post(sefl):
        id = request.json.get('id')
        desc = db.session.query(Desc).filter(Desc.id == id).first()
        if desc:
            desc.title = request.json.get('title')
            desc.desc = request.json.get('desc')
            db.session.commit()
        return {
                'code': 200,
                'msg': '修改成功'
            }


class GoodnessResource(Resource):

    def get(self):
        result = db.session.query(OursGoodness).order_by('-id').first()

        return marshal({
            'code': 200,
            'msg': '获取成功',
            'data': result
        }, GoodnessFields)

    def put(self):

        content = request.json.get('content', '')
        goodness = OursGoodness(content=content)
        db.session.add(goodness)
        db.session.commit()

        return marshal({
            'code': 200,
            'msg': '获取成功',
            'data': goodness
        }, GoodnessFields)


class ProductExamplesResource(Resource):

    def get(self):
        result = db.session.query(ProductExamples).order_by('-id').all()
        P = Page(result)
        return marshal({
            'code': 200,
            'msg': '获取成功',
            'data': P.data,
            'page': P.page_info
        }, ProductExamplesFields)

    def put(self):
        img = request.json.get('img')
        desc = request.json.get('desc')
        print(request.json)
        E = ProductExamples(img=img, desc=desc)

        db.session.add(E)
        db.session.commit()
        return marshal({
            'code': 200,
            'msg': '新建成功',
            'data': E
        }, ProductOneExamplesFields)

    def post(self):
        id = request.json.get('id')
        img = request.json.get('img')
        desc = request.json.get('desc')
        print(request.json)
        E = db.session.query(ProductExamples).filter(
            ProductExamples.id == id).first()
        if not E:
            return {
                'code': 404,
                'msg': '未找到',
            }
        E.img = img
        E.desc = desc
        db.session.commit()
        return marshal({
            'code': 200,
            'msg': '修改成功',
            'data': E
        }, ProductOneExamplesFields)

    def delete(self):
        id = request.args.get('id')
        E = db.session.query(ProductExamples).filter(
            ProductExamples.id == id).first()
        if E:
            db.session.delete(E)
            db.session.commit()
        return {
                'code': 200,
                'msg': '删除成功',
            }


class ArticleResource(Resource):

    def get(self):
        title = request.args.get('title', '')
        result = db.session.query(Article).filter(
            Article.title.like('%%%s%%' % title)).all()
        P = Page(result)
        return marshal({
            'code': 200,
            'msg': '获取成功',
            'data': P.data,
            'page': P.page_info
        }, ArticleFields)

    def put(self):
        title = request.json.get('title')
        content = request.json.get('content')

        A = Article(title=title, content=content)

        db.session.add(A)
        db.session.commit()
        return {
            'code': 200,
            'msg': '新建成功'
        }

    def delete(self):
        id = request.args.get('id')
        A = db.session.query(Article).filter(Article.id == id).first()
        if A:
            db.session.delete(A)
            db.session.commit()

        return {
            'code': 200,
            'msg': '删除成功'
        }


class ArticleOneResource(Resource):

    def get(self, id):
        A = db.session.query(Article).filter(Article.id == id).first()
        if not A:
            return {
            'code': 404,
            'msg': '未找到',

        }
        return {
            'code': 200,
            'msg': '获取成功',
            'data': {
                'id': A.id,
                'title': A.title,
                'content': A.content
            }
        }

    def post(self, id):
        A = db.session.query(Article).filter(Article.id == id).first()
        if not A:
            return {
                'code': 404,
                'msg': '未找到',

            }
        A.title = request.json.get('title')
        A.content = request.json.get('content')
        db.session.commit()
        return {
            'code': 200,
            'msg': '修改成功'
        }


class ProductResource(Resource):

    def get(self):

        result = db.session.query(Product).filter(Product.use == True).all()
        P = Page(result)
        return marshal(
            {
                'code': 200,
                'msg': '获取成功',
                'data': P.data,
                'page': P.page_info
            },
            ProductListFields
        )

    def delete(self):

        id = request.args.get('id')
        instance = db.session.query(Product).filter(Product.id == id).first()

        if instance:
            print(instance)
            instance.use = False
            db.session.commit()

        return {
            'code': 200,
            'msg': '删除成功'
        }

    def post(self):

        data = UpdataProduct.parse_args(req=request)

        instance = db.session.query(Product).filter(
            Product.id == data['id']).first()

        if instance:
            instance.name = data['name']
            instance.desc = data['desc']
            instance.img = data['img']
            exists_ids = [i['id']
                          for i in request.json['types'] if i['id'] > 0]
            try:
                exists = [
                    ProductType(id=i['id'], price=float(
                        i['price']), name=i['name'], desc=i['desc'],type=i['type'],f_limit=i['f_limit'])
                    for i in request.json['types']
                    if i['id'] > 0 and (i.pop('edit', None) or True)
                ]
            except Exception as e:
                print(e)
                return {
                    'code': 400,
                    'msg': '初始化数据异常'
                }

            created = [i for i in request.json['types'] if i['id'] < 0]

            for i in instance.types:
                result = [i for i in filter(lambda x: x.id == i.id, exists)]
                print(result)
                if not result:
                    db.session.delete(i)

                else:
                    update = result[0]
                    print(update == i)
                    if update != i:
                        i.name = update.name
                        i.desc = update.desc
                        i.price = update.price
                        i.type = update.type
                        i.f_limit = update.f_limit

            for i in created:
                i.pop('id', None) and i.pop('edit', None)
                try:
                    price = float(i.pop('price'))
                except Exception as e:
                    pass
                else:
                    print('test')
                    db.session.add(ProductType(
                        price=price, product_id=instance.id, **i))

            db.session.commit()

        return {
            'code': 200,
            'msg': '修改成功'
        }

    def put(self):
        data = CreateProduct.parse_args(req=request)
        instance = Product(
            img=request.json['img'],
            desc=request.json['desc'],
            name=request.json['name']
        )
        for i in request.json['types']:
            i.pop('id', None) and i.pop('edit', None)
            try:
                price = float(i.pop('price'))
            except Exception as e:

                pass
            else:
                print('test')
                db.session.add(ProductType(
                    price=price, product=instance, **i))
        db.session.add(instance)
        db.session.commit()

        return {
            'code': 200,
            'msg': '添加成功',
        }


class ProductOneResource(Resource):

    def get(self, id):

        instance = db.session.query(Product).filter(Product.id == id).first()
        if not instance:
            return {
                'code': 404,
                'msg': '未找到'
            }
        return marshal({
            'code': 200,
            'msg': '获取成功',
            'data': instance
        }, ProductALLFields)


class AliPayCallBack(Resource):

    def get(self):

        data = request.args.to_dict()
        # sign 不能参与签名验证
        signature = data.pop("sign")

        success = AliPayComponent().verify(data, signature)
        if success:
            out_trade_no = data['out_trade_no']
            trade_no = data['trade_no']
            order = db.session.query(Order).filter(
                Order.order_number == out_trade_no).first()
            if not order:
                return {
                    'code': 400,
                    'msg': '服务器异常请联系管理员'
                }
            if order.is_pay:
                return redirect('/#/sending/%s/?trade_no=%s&sign=%s' % (order.id, trade_no, signature))
            order.is_pay = True
            order.trade_no = trade_no
            if order.is_distribution:
                user = db.session.query(FrontUser).join(
                    Order, FrontUser.login_name == Order.distribution).first()
                setting = db.session.query(Setting).order_by('-id').first()
                if user.level == 1:
                    user.commission += order.pay_number * setting.level_1
                elif user.level == 2:
                    user.commission += order.pay_number * setting.level_2
                else:
                    user.commission += order.pay_number * setting.level_3
            db.session.commit()
            send_email.delay(order=order.id)
            return redirect('/#/sending/%s/?trade_no=%s&sign=%s' % (order.id, trade_no, signature))
        else:
            return {
                'code': 400,
                'msg': '服务器异常请联系管理员'
            }

    def post(self):
        data = request.form.to_dict()
        print(data)
        # sign 不能参与签名验证
        signature = data.pop("sign")

        success = AliPayComponent().verify(data, signature)
        if success:

            order = db.session.query(Order).filter(
                Order.order_number == data['out_trade_no']).first()
            if order and order.is_pay:

                return 'success'
            else:
                if not order:
                    order = db.session.query(Distribution).filter(
                        Distribution.order_number == data['out_trade_no']).first()
                    if order and order.is_pay:
                        return 'success'

                    if order and not order.is_pay:
                        order.user.is_distribution = True
                        order.user.level = order.level
                        order.is_pay = True
                        order.trade_no = data['trade_no']
                        db.session.commit()
                        db.session.commit()
                        return 'success'

                if not order.is_pay:
                    order.is_pay = True
                    if order.is_distribution:
                        user = db.session.query(FrontUser).join(Order, FrontUser.login_name == Order.distribution).filter(
                            Order.distribution == order.distribution
                        ).first()
                        setting = db.session.query(
                            Setting).order_by('-id').first()
                        if user.level == 1:
                            user.commission += order.pay_number * setting.level_1
                        elif user.level == 2:
                            user.commission += order.pay_number * setting.level_2
                        else:
                            user.commission += order.pay_number * setting.level_3
                    order.trade_no = data['trade_no']
                    db.session.commit()
                    db.session.commit()
                return 'success'

        else:
            return 'failure'


class OrderResource(Resource):

    def post(self):

        products = request.json.get('products')
        dev = request.json.get('dev')
        channels = request.json.get('channels', 'alipay')
        sign = request.json.get('sign')
        distribution = request.json.get('distribution')

        total = 0
        subject = ''

        for i in products:
            print(i)
            product = db.session.query(ProductType).filter(
                ProductType.id == i['id']).first()
            if not products:
                return {
                    'code': 404,
                    'msg': '%s 商品管理员已下架，请重新下单' % (i['name'])
                }
            try:
                if float(product.price) != float(i['price']):
                    return {
                        'code': 400,
                        'msg': '%s 商品价格已变动，请重新下单' % (i['name'])
                    }
            except Exception as e:
                return {
                    'code': 400,
                    'msg': '%s 商品价格已变动，请重新下单' % (i['name'])
                }
            try:
                number = int(i['number'])
                assert number > 0, Exception('错误的数据')
            except Exception as e:
                return {
                    'code': 400,
                    'msg': '数据异常'
                }
            total += product.price * number
            subject = '%s,%s' % (subject, product.name)
        D = db.session.query(Distribution).join(FrontUser, Distribution.user_id == FrontUser.id).filter(FrontUser.login_name == distribution,
                                FrontUser.login_slot == sign).first()
        if D:

            order = Order(
                pay_channels=2 if channels == 'alipay' else 1,
                pay_number=total,
                is_pay=False,
                is_distribution=True,
                distribution=D.user.login_name
            )
        else:
            order = Order(
                pay_channels=2 if channels == 'alipay' else 1,
                pay_number=total,
                is_pay=False,
            )

        for i in products:
            order_products = Order2Product(
                number=i['number'], email=i['email'])
            order_products.order = order
            order_products.product = db.session.query(ProductType).filter(
                ProductType.id == i['id']).first()
            for i in range(int(i['number'])):
                use_number = UseNumber(is_use=True)
                use_number.Order2Product = order_products

        db.session.add(order)
        db.session.commit()
        redirect_url = ''
        if dev == 'phone' and channels == 'alipay':
            redirect_url = AliPayComponent().make_trade_for_phone(
                subject, float(total), order.order_number)
        elif dev == 'pc' and channels == 'alipay':
            redirect_url = AliPayComponent().make_trade_for_pc(
                subject, float(total), order.order_number)

        return {
            'code': 200,
            'msg': '获取成功',
            'data': {
                'redirect': redirect_url,
                'order': order.id
            }
        }


class OrderOneResource(Resource):

    def get(self, id):
        sign = request.args.get('sign')
        trade_no = request.args.get('trade_no')
        if not sign or not trade_no:
            return {
                'code': 404,
                'msg': '未找到'
            }

        order = db.session.query(Order).filter(
            Order.id == id, Order.trade_no == trade_no).first()
        if not order:
            return {
                'code': 404,
                'msg': '未找到'
            }

        return marshal({
            'code': 200,
            'msg': '获取成功',
            'data': order
        }, OrderOneFields)


class UseCard(Resource):

    def post(self):
        id = request.json.get('id')
        types = request.json.get('type','')

        

        card = db.session.query(UseNumber).filter(
            UseNumber.card_number == id).first()
        
        if not card:
            return {
                'code': 404,
                'msg': '未找到激活码'
            }

        if card.is_use:
            return {
                'code': 400,
                'msg': '激活码已经被使用'
            }
        
        if card.Order2Product.product.type != int(types):
            return {
                'code': 404,
                'msg': '未找到激活码'
            }

        
        return {
            'code': 200,
            'msg': '获取成功',
            'data': {
                'card_number': card.card_number,
                'is_use': False,
                'type': {
                    'name': card.Order2Product.product.name,
                    'desc': card.Order2Product.product.desc,
                    'price': str(card.Order2Product.product.price),
                    'type':card.Order2Product.product.type
                }
            }
        }


class OrderList(Resource):

    def get(self):

        result = db.session.query(Order).all()
        P = Page(result)
        return marshal({
            'code': 200,
            'msg': '获取成功',
            'data': P.data,
            'page': P.page_info
        }, OrderListFields)


class TutorialsResource(Resource):

    def get(self):
        result = db.session.query(Tutorials).all()
        P = Page(result)
        return marshal(
            {
                'code': 200,
                'msg': '获取成功',
                'data': P.data,
                'page': P.page_info
            },
            TutorialsFields
        )

    def put(self):
        try:

            T = Tutorials(**request.json)
        except Exception as e:
            return {
                'code': 400,
                'msg': '数据错误'
            }
        db.session.add(T)
        db.session.commit()

        return marshal(
            {
                'code': 200,
                'msg': '新建成功',
                'data': T,
            },
            TutorialsOneFields
        )

    def delete(self):

        id = request.args.get('id')
        D = db.session.query(Tutorials).filter(Tutorials.id == id).first()

        if D:
            db.session.delete(D)

            db.session.commit()

        return {
            'code': 200,
            'msg': '删除成功'
        }

    def post(self):
        id = request.json.get('id')
        video = request.json.get('video')
        desc = request.json.get('desc')
        D = db.session.query(Tutorials).filter(Tutorials.id == id).first()
        D.video = video
        D.desc = desc
        db.session.commit()

        return {
            'code': 200,
            'msg': '修改成功'
        }


class FrontLogin(Resource):

    def get(self):
        username = request.args.get('username')
        if not username:
            return {
                'code': 404,
                'msg': '未找到'
            }
        user = db.session.query(FrontUser).filter(
            FrontUser.login_name == username).first()
        if not user:
            return {
                'code': 404,
                'msg': '未找到'
            }
        return {
            'code': 200,
            'msg': '获取成功',
            'data': {
                'avatar': user.avatar
            }
        }

    def post(self):
        inputs = LOGIN_VALID.parse_args(req=request)
        if inputs:
            username = inputs['username']
            password = inputs['password']
            user = db.session.query(FrontUser).filter(
                FrontUser.login_name == username).first()
            if not user:
                return {
                    'code': 403,
                    'msg': '找不到用户'
                }

            if user.status != 1:
                return {
                    'code': 403,
                    'msg': '账号未激活'
                }

            elif user.checkPassWord(password):
                return {
                    'code': 200,
                    'token': user.get_jwt_str(),
                    'permission': ['user']
                }
            else:
                return {
                    'code': 403,
                    'msg': '用户名或密码错误'
                }
        else:
            error_message = forms.errors.popitem()
            return {
                'code': 403,
                'msg': error_message[1][0]
            }

    def put(self):
        inputs = LOGIN_VALID.parse_args(req=request)
        username = inputs['username']
        password = inputs['password']
        user = db.session.query(FrontUser).filter(
                FrontUser.login_name == username).first()
        if user and user.status == 1:
            return {
                'code': 400,
                'msg': '用户已经存在'
            }

        if not user:
            user = FrontUser(login_name=username,
                             login_pwd=password, status=2, commission=0)
            db.session.add(user)
            db.session.commit()

        send_url = '%s/api/register/check/?username=%s&sign=%s' % (
            current_app.config['DOMAIN'], user.login_name, user.login_slot)
        send_email_register.delay(email_addr=username, url=send_url)

        return {
            'code': 200,
            'msg': '注册成功，请查收激活邮件'
        }


class RegisterCheck(Resource):

    def get(self):

        username = request.args.get('username')
        sign = request.args.get('sign')

        user = db.session.query(FrontUser).filter(
                FrontUser.login_name == username, FrontUser.login_slot == sign).first()

        if user:
            user.status = 1
            db.session.commit()

        return redirect('/')


class Profile(Resource):

    def get(self):

        return marshal(
            {
                'code': 200,
                'msg': '获取成功',
                'data': g.user
            },
            FrontUseOnerFields
        )

    def post(self):
        avatar = request.json.get('avatar')
        nick_name = request.json.get('nick_name')

        if avatar:
            g.user.avatar = avatar

        if nick_name:
            g.user.nick_name = nick_name

        db.session.commit()

        return {
            'code': 200,
            'msg': '修改成功',
            'data': {
                'token': g.user.get_jwt_str()
            }
        }


class MakeDistribution(Resource):

    def post(self):

        types = request.json.get('type')
        price = request.json.get('price')
        channels = request.json.get('channels', 'alipay')
        dev = request.json.get('dev', 'phone')

        setting = db.session.query(Setting).order_by('-id').first()
        if types == 1:
            price = setting.level_1_price
        elif types == 2:
            price = setting.level_2_price
        else:
            price = setting.level_3_price

        if float(price) != float(price):
            return {
                'code': 400,
                'msg': '服务器繁忙请稍后重试'
            }
        d = Distribution(
                pay_number=float(price),
                pay_channels=2 if channels == 'alipay' else 1,
                user_id=g.user.id,
                level=types
            )
        db.session.add(d)
        db.session.commit()
        if dev == 'phone' and channels == 'alipay':

            redirect_url = AliPayComponent().make_trade_for_phone(
                '分销商', float(price), d.order_number, return_url='%s/api/distribution/' % (current_app.config['DOMAIN']))
        elif dev == 'pc' and channels == 'alipay':
            redirect_url = AliPayComponent().make_trade_for_pc(
                '分销商', float(price), d.order_number, return_url='%s/api/distribution/' % (current_app.config['DOMAIN']))

        return {
            'code': 200,
            'msg': '获取成功',
            'data': {
                'redirect': redirect_url,
                'order': d.id
            }
        }

    def get(self):
        data = request.args.to_dict()
        # sign 不能参与签名验证
        signature = data.pop("sign")

        success = AliPayComponent().verify(data, signature)
        if success:
            out_trade_no = data['out_trade_no']
            trade_no = data['trade_no']
            order = db.session.query(Distribution).filter(
                Distribution.order_number == out_trade_no).first()
            if not order:
                return {
                    'code': 400,
                    'msg': '服务器异常请联系管理员'
                }
            if order.is_pay:
                return redirect('/' % (order.id, trade_no, signature))
            order.user.is_distribution = True
            order.user.level = order.level
            order.is_pay = True
            order.trade_no = trade_no
            db.session.commit()
            return redirect('/' % (order.id, trade_no, signature))
        else:
            return {
                'code': 400,
                'msg': '服务器异常请联系管理员'
            }


class transfer(Resource):

    def post(self):
        user = g.user
        price = request.json.get('price')
        alipay_account = request.json.get('alipayAccount')
        rel_name = request.json.get('relName')

        if not alipay_account or not rel_name:
            return {
                'code': 400,
                'msg': '服务器繁忙'
            }

        if price:
            if float(price) > float(user.commission):
                return {
                    'code': 400,
                    'msg': '服务器繁忙'
                }
        else:
            price = user.commission

        if price <= 0:
            return {
                    'code': 400,
                    'msg': '服务器繁忙'
                }
        T = TransferHistory(
            user_id=user.id, transfer_number=price, transfer_channels=2,alipay_account=alipay_account)
        db.session.add(T)
        db.session.commit()
        user.commission -= price
        print(T.transfer_id)
        try:
            response = AliPayComponent().transfer(
                alipay_account, float(price), rel_name, T.transfer_id)
        except Exception as e:
            return {
                    'code': 400,
                    'msg': '服务器繁忙'
                }
        if response['msg'] == 'Success' and response['code'] == '10000':
            T.is_transfer= True
            T.trade_no= response['order_id']
        elif response['msg'] == 'Success' and response['code'] == '10000':
            pass
        else :
            return {
                    'code': 400,
                    'msg': '服务器繁忙'
                }
        db.session.commit()

        return {
                    'code': 200,
                    'msg': '提现成功'
                }